﻿namespace Pibby.Core.IO
{
	using System;
	using invrt;

	public static class DriveFinder
	{
		public static bool IsDriveConnected(string driveId)
		{
			return DriveFinder.FindDrive(driveId) != null;
		}
		
		public static IDrive FindDrive(string driveName)
		{
			IDriveFactory factory = InversionOfController.Factory.CreateTypeOf<IDriveFactory>();

			return FindDrive(driveName, factory);
		}

		public static IDrive FindDrive(string driveName, IDriveFactory factory)
		{
			if (!string.IsNullOrEmpty(driveName))
			{
				IDriveCollection driveList = factory.GetAllDrives();

				foreach (IDrive drive in driveList)
				{
					try
					{
						if (drive.Name.Equals(driveName, StringComparison.CurrentCultureIgnoreCase))
						{
							return drive;
						}
					}
					catch (System.IO.IOException)
					{
						// may be trying to connect to drives that are not ready - swallow this exception
					}
				}
			}

			return null;
		}
	}
}
